<template>
  <view class="match-table-wrapper">
    <view class="header h-44rpx mt-24rpx mb-16rpx">晋级人数 1</view>
    <view class="border-rd-24rpx bg-white">
      <view class="table-container" v-if="tableData.length">
        <scroll-view scroll-x="true">
          <view class="table">
            <view class="table-row table-header">
              <view v-for="(cell, index) in tableData[0]" :key="index" class="table-cell">
                {{ cell }}
              </view>
            </view>
            <view v-for="(row, rowIndex) in tableData.slice(1)" :key="rowIndex" class="table-row">
              <view
                v-for="(cell, cellIndex) in row"
                :key="cellIndex"
                class="table-cell"
                :class="{ 'player-name': cellIndex === 0 }"
              >
                {{ cell }}
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { EventToPlayer, Group, GroupPlayerScore, Match } from '@/championship'
import { MatchStatusEnum } from '@/common/enum'
import { ref } from 'vue'

const props = defineProps<{
  groupInfo: Group
  players: EventToPlayer[]
}>()

const tableData = ref([])

function generateGroupMatchTable(
  // matches: Match[],
  // playerMap: { [playerId: string]: string },
  groupInfo: Group,
): any[][] {
  const matches = groupInfo.matchInfos
  const scoreInfo = groupInfo.groupPlayerScores || []
  const playerMap: Record<string, EventToPlayer> = matches.reduce((total, item) => {
    const { homePlayer, awayPlayer } = item
    total[homePlayer.id] = homePlayer
    total[awayPlayer.id] = awayPlayer
    return total
  }, {})
  // const playerMap: Record<string, EventToPlayer> = scoreInfo.reduce((total, item) => {
  //   item.player && (total[item.player.id] = item.player)
  //   return total
  // }, {})
  const scoreMap: { [key: number]: GroupPlayerScore } = scoreInfo.reduce((total, item) => {
    item.player && (total[item.player.id] = item)
    return total
  }, {})

  // 2. 初始化结果数组
  const resultMap: Record<string, any> = {}
  Object.entries(playerMap).forEach(([key, value]) => {
    const rowData: Record<string, string> = {}
    rowData.name = `${value.player1Name}${value.player2Name ? ' ' + value.player2Name : ''}`
    Object.entries(playerMap).forEach(([key2, value2]) => {
      rowData[key2] = ''
    })
    const scoreInfo = scoreMap[Number(key)]
    if (!scoreInfo) {
      resultMap[key] = rowData
      return
    }
    rowData.match =
      `${scoreInfo.winMatchCount - scoreInfo.loseMatchCount}(${scoreInfo.winMatchCount}-${scoreInfo.loseMatchCount})` ||
      '-'
    rowData.game =
      `${scoreInfo.winGameCount - scoreInfo.loseGameCount}(${scoreInfo.winGameCount}-${scoreInfo.loseGameCount})` ||
      '-'
    rowData.rally =
      `${scoreInfo.winRallyCount - scoreInfo.loseRallyCount}(${scoreInfo.winRallyCount}-${scoreInfo.loseRallyCount})` ||
      '-'
    rowData.match = `${scoreInfo.winMatchCount}`
    rowData.netWin = `${scoreInfo.winMatchCount - scoreInfo.loseMatchCount}`
    rowData.range = '-'
    rowData.winMatchCount = `${scoreInfo.winMatchCount}`
    rowData.loseMatchCount = `${scoreInfo.loseMatchCount}`
    rowData.winGameCount = `${scoreInfo.winGameCount}`
    rowData.loseGameCount = `${scoreInfo.loseGameCount}`
    rowData.winRallyCount = `${scoreInfo.winRallyCount}`
    rowData.loseRallyCount = `${scoreInfo.loseRallyCount}`
    resultMap[key] = rowData
  })
  // const resultMap: any[][] = playerIds.map((id) => [
  //   // playerMap[id],
  //   id.player1Name,
  //   ...Array(playerIds.length + 4).fill('-'),
  // ])

  // 3. 填充比分和计算胜场
  matches.forEach((match) => {
    const homeId = match.homePlayer.id
    const awayId = match.awayPlayer.id
    const status = match.status

    const showType = (x, y) => {
      if (x < y) {
        return 'detail'
      } else if (x > y) {
        return 'total'
      }
    }
    const getDetailRally = (match: Match, type: 1 | 2) => {
      if (type === 1) {
        return `${match.homePlayerRally}-${match.awayPlayerRally} \n`
      } else {
        return `${match.awayPlayerRally}-${match.homePlayerRally} \n`
      }
    }
    const getTotalRally = (match: Match, type: 1 | 2) => {
      let msg = ''
      if (match.games?.length > 0) {
        match.games.forEach((game) => {
          if (type === 1) {
            msg += `${game.homePlayerRally}:${game.awayPlayerRally} \n`
          } else {
            msg += `${game.awayPlayerRally}:${game.homePlayerRally} \n`
          }
        })
      }
      return msg
    }
    if (homeId && awayId && status === MatchStatusEnum.Finished) {
      if (showType(homeId, awayId) === 'detail') {
        resultMap[homeId][awayId] += getDetailRally(match, 1)
      }
      if (showType(homeId, awayId) === 'total') {
        resultMap[homeId][awayId] += getTotalRally(match, 1)
      }
      if (showType(awayId, homeId) === 'detail') {
        resultMap[awayId][homeId] += getDetailRally(match, 2)
      }
      if (showType(awayId, homeId) === 'total') {
        resultMap[awayId][homeId] += getTotalRally(match, 2)
      }
    }
  })
  const headerNames = []
  const tableData = Object.values(resultMap)
    .sort((a, b) => {
      return Number(b.winMatchCount) - Number(a.winMatchCount)
    })
    .map((item, index) => {
      headerNames.push(item.name)
      const row = [
        item.name,
        ...Object.values(item).slice(0, Object.values(playerMap).length),
        item.match,
        item.netWin,
        index + 1,
      ]
      return row
    })

  // 6. 添加表头
  const header = ['选手', ...headerNames, '胜场', '净胜', '排名']
  tableData.unshift(header)

  return tableData
}

watchEffect(() => {
  // const playerMap = props.players.reduce(
  //   (map, player) => {
  //     map[player.registrationIndex] = player.player?.name || player.registrationIndex
  //     return map
  //   },
  //   {} as { [playerId: string]: string },
  // )
  tableData.value = generateGroupMatchTable(props.groupInfo)
})
</script>
<style lang="scss" scoped>
.match-table-wrapper {
  .table-container {
    width: 100%;
    overflow-x: auto;
  }

  .table {
    display: table;
    white-space: nowrap;
    border-collapse: collapse;
  }

  .table-row {
    display: table-row;
  }

  .table-cell {
    display: table-cell;
    min-width: 150rpx;
    padding: 10rpx 15rpx;
    text-align: center;
    white-space: pre-wrap;
    vertical-align: middle;
    border: 1rpx solid #e0e0e0;
  }

  .table-header {
    font-weight: bold;
    background-color: #f5f5f5;
  }

  .player-name {
    position: sticky;
    left: 0;
    z-index: 1;
    font-weight: bold;
    background-color: #f5f5f5;
  }
  /* 确保表头的第一个单元格在滚动时始终可见 */
  .table-header .table-cell:first-child {
    position: sticky;
    left: 0;
    z-index: 2;
    background-color: #f5f5f5;
  }
}
</style>
